package com.jian.android.autojipai;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.NotificationManagerCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.jian.android.autojipai.app.App;
import com.jian.android.autojipai.app.MediaProjectionService;
import com.jian.android.autojipai.app.helper.DialogTool;
import com.jian.android.autojipai.app.helper.FloatingOnTouchListener;
import com.jian.android.autojipai.app.helper.LogTool;
import com.jian.android.autojipai.app.helper.NoDoubleClickTool;
import com.jian.android.autojipai.app.helper.PokerDataHandleTool;
import com.jian.android.autojipai.app.helper.StringTool;
import com.jian.android.autojipai.app.helper.SystemTool;
import com.jian.android.autojipai.app.helper.ToastTool;
import com.jian.android.autojipai.data.bean.EventBusOb;
import com.jian.android.autojipai.data.bean.Poker;
import com.jian.android.autojipai.ui.page.adapter.AutoPokerRvAdapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivityAuto extends Activity implements View.OnClickListener {
    private List<Poker> allPokerList = new ArrayList();
    private AutoPokerRvAdapter autoPokerRvAdapter;
    private Button btn;
//    private ConfigureFromGitee configureFromGitee;
    private View mFloatingView;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams params;
    private ProgressDialog progressDialog;
    private RecyclerView rvPoker;
    private TextView tv_notice;

    @Override
    protected void onCreate(Bundle bundle) {

        super.onCreate(bundle);
        if (SystemTool.getInstance().isNetworkAvailable(this)) {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            setContentView(R.layout.activity_main_auto);
            initViews();
        } else {
            DialogTool.getInstance().showTipDialog(this, "本App需要联网使用");
        }
    }

    private void initViews() {
        ProgressDialog progressDialog = new ProgressDialog(this, R.style.ProgressDialogStyle);
        this.progressDialog = progressDialog;
        progressDialog.setCancelable(true);
        this.progressDialog.setCanceledOnTouchOutside(false);
        this.tv_notice = (TextView) findViewById(R.id.tv_notice);
        Button button = (Button) findViewById(R.id.btn);
        this.btn = button;
        button.setOnClickListener(this);
        findViewById(R.id.rl_share_app).setOnClickListener(this);
        findViewById(R.id.rl_my_wx).setOnClickListener(this);
        findViewById(R.id.rl_wx_group).setOnClickListener(this);
        findViewById(R.id.rl_wxgzh).setOnClickListener(this);
        findViewById(R.id.rl_feedback).setOnClickListener(this);
        findViewById(R.id.rl_check).setOnClickListener(this);
        findViewById(R.id.rl_use_know).setOnClickListener(this);
        findViewById(R.id.rl_copy_id).setOnClickListener(this);
        findViewById(R.id.rl_price).setOnClickListener(this);
        TextView textView = (TextView) findViewById(R.id.tv_version_name);
        textView.setText("版本名：" + StringTool.getVersionName(this));

        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(displayMetrics);
        int i = displayMetrics.widthPixels;
        int i2 = displayMetrics.heightPixels;
        App.height = i2;
        App.width = i;
        App.dpi = displayMetrics.densityDpi;
        LogTool.getInstance().printLog("TAG", i + "_屏幕实际宽度");
        LogTool.getInstance().printLog("TAG", i2 + "_屏幕实际高度");
    }

    @Override // android.app.Activity
    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i == 25) {
            if (Settings.canDrawOverlays(this)) {
                startActivityForResult(((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)).createScreenCaptureIntent(), 26);
            } else {
                ToastTool.getInstance().show(this, "您没有授予悬浮窗权限");
            }
        }
        if (i == 26 && i2 == Activity.RESULT_OK) {
            Intent intent2 = new Intent(this, MediaProjectionService.class);
            intent2.putExtra("code", i2);
            intent2.putExtra("data", intent);
            intent2.putExtra("width", App.width);
            intent2.putExtra("height", App.height);
            intent2.putExtra("dpi", App.dpi);
            if (Build.VERSION.SDK_INT >= 26) {
                startForegroundService(intent2);
            } else {
                startService(intent2);
            }
            if (this.mWindowManager != null && this.mFloatingView != null && this.params != null) {
                if (Build.VERSION.SDK_INT != 26) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                this.mWindowManager.addView(this.mFloatingView, this.params);
                this.btn.setText("点击停止");
                moveTaskToBack(true);
                return;
            }
            final String[] strArr = {"跑的快[16张]", "跑的快[15张]", "1副牌"};
            new AlertDialog.Builder(this).setTitle((CharSequence) "请选择几副牌、玩法").setItems((CharSequence[]) strArr, new DialogInterface.OnClickListener() {
                @Override // android.content.DialogInterface.OnClickListener
                public void onClick(DialogInterface dialogInterface, int i3) {
                    if (dialogInterface != null) {
                        dialogInterface.dismiss();
                    }
                    if (Build.VERSION.SDK_INT != 26) {
                        MainActivityAuto.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }
                    App.type = strArr[i3];
                    MainActivityAuto.this.initFloat();
                    MainActivityAuto.this.btn.setText("点击停止");
                    MainActivityAuto.this.moveTaskToBack(true);
                }
            }).show();
        }
    }

    public void initFloat() {
        this.mFloatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_bottom_auto, (ViewGroup) null);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(-1, -2, Build.VERSION.SDK_INT >= 26 ? 2038 : 2002, 8, -3);
        this.params = layoutParams;
        layoutParams.gravity = Gravity.BOTTOM;
        this.params.x = 0;
        this.params.y = 0;
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        this.mWindowManager = windowManager;
        windowManager.addView(this.mFloatingView, this.params);
        this.mFloatingView.setOnTouchListener(new FloatingOnTouchListener(this.params, this.mWindowManager, this.mFloatingView));
        final TextView textView = (TextView) this.mFloatingView.findViewById(R.id.tv_state);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (NoDoubleClickTool.isFastDoubleClick()) {
                    return;
                }
                String charSequence = textView.getText().toString();
                if ("开始".equals(charSequence)) {
                    textView.setText("停止");
                    PokerDataHandleTool.getInstance().setAllPokerDataIsEmpty();
                    MainActivityAuto.this.allPokerList.clear();
                    String str = App.type;
                    if ("跑的快[16张]".equals(str)) {
                        MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers16(1));
                    }
                    if ("跑的快[15张]".equals(str)) {
                        MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers15(1));
                    }
                    if ("1副牌".equals(str)) {
                        MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPokers1(1));
                    }
                    MainActivityAuto.this.autoPokerRvAdapter.notifyDataSetChanged();
                    App.isStartDetection = true;
                    App.isCanDetection = true;
                    EventBus.getDefault().post("getBitmap");
                } else if ("停止".equals(charSequence)) {
                    textView.setText("开始");
                    App.isStartDetection = false;
                    PokerDataHandleTool.getInstance().setAllPokerDataIsEmpty();
                    MainActivityAuto.this.allPokerList.clear();
                    String str2 = App.type;
                    if ("跑的快[16张]".equals(str2)) {
                        MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers16(1));
                    }
                    if ("跑的快[15张]".equals(str2)) {
                        MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers15(1));
                    }
                    if ("1副牌".equals(str2)) {
                        MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPokers1(1));
                    }
                    MainActivityAuto.this.autoPokerRvAdapter.notifyDataSetChanged();
                }
            }
        });
        RecyclerView recyclerView = (RecyclerView) this.mFloatingView.findViewById(R.id.rv_poker);
        this.rvPoker = recyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        String str = App.type;
        if ("跑的快[16张]".equals(str)) {
            this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers16(1));
        }
        if ("跑的快[15张]".equals(str)) {
            this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers15(1));
        }
        if ("1副牌".equals(str)) {
            this.allPokerList.addAll(Poker.getAutoPokers1(1));
        }
        AutoPokerRvAdapter autoPokerRvAdapter = new AutoPokerRvAdapter(this.allPokerList);
        this.autoPokerRvAdapter = autoPokerRvAdapter;
        this.rvPoker.setAdapter(autoPokerRvAdapter);
    }

    @Override
    public void onClick(View view) {
        WindowManager windowManager;
        View view2;
        if (NoDoubleClickTool.isFastDoubleClick()) {
            return;
        }
        int id = view.getId();
        if (id == R.id.btn) {
            String trim = this.btn.getText().toString().trim();
            if (trim.equals("点击启动")) {
                if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
                    DialogTool.getInstance().showNotificationDialog(this);
                } else if (!SystemTool.getInstance().isNetworkAvailable(this)) {
                    ToastTool.getInstance().show(this, "网络不可用");
                } else if (!new File(getFilesDir() + File.separator + "1.tflite").exists()) {
                    ToastTool.getInstance().show(this, "请稍后重试");
                } else {
                        if (!Settings.canDrawOverlays(MainActivityAuto.this)) {
                            MainActivityAuto.this.startActivityForResult(new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION", Uri.parse("package:" + MainActivityAuto.this.getPackageName())), 25);
                            return;
                        }
                        MainActivityAuto.this.startActivityForResult(((MediaProjectionManager) MainActivityAuto.this.getSystemService(Context.MEDIA_PROJECTION_SERVICE)).createScreenCaptureIntent(), 26);
                }
            } else if (!trim.equals("点击停止") || (windowManager = this.mWindowManager) == null || (view2 = this.mFloatingView) == null) {

            } else {
                try {
                    windowManager.removeView(view2);
                    this.btn.setText("点击启动");
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastTool.getInstance().show(this, "停止发生错误!");
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusOb eventBusOb) {
        LogTool.getInstance().printLog("---Main", "onMessageEvent：" );
        if (eventBusOb ==null){
            return;
        }
        if ("restart".equals(eventBusOb.getMsg())){
            reset();
        }else if ("updateUI".equals(eventBusOb.getMsg())) {
            List<Poker> pokerList = eventBusOb.getPokerList();
            LogTool.getInstance().printLog("---Main", "pokerList："+pokerList.size() );
            this.allPokerList.clear();
            this.allPokerList.addAll(pokerList);
            if (autoPokerRvAdapter != null) {
                autoPokerRvAdapter.notifyDataSetChanged();
            }
            App.isCanDetection = true;

        }

    }

    private void reset(){
        LogTool.getInstance().printLog("---Main", "reset：" );
        PokerDataHandleTool.getInstance().setAllPokerDataIsEmpty();
        MainActivityAuto.this.allPokerList.clear();
        String str = App.type;
        if ("跑的快[16张]".equals(str)) {
            MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers16(1));
        }
        if ("跑的快[15张]".equals(str)) {
            MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPaoDeKuaiPokers15(1));
        }
        if ("1副牌".equals(str)) {
            MainActivityAuto.this.allPokerList.addAll(Poker.getAutoPokers1(1));
        }
        MainActivityAuto.this.autoPokerRvAdapter.notifyDataSetChanged();
    }

    @Override // android.app.Activity
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override // android.app.Activity
    public void onDestroy() {
        View view;
        try {
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
            WindowManager windowManager = this.mWindowManager;
            if (windowManager != null && (view = this.mFloatingView) != null) {
                windowManager.removeView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}
